package com.lanou.bookstore.user.web.servlet;

import com.lanou.bookstore.user.dao.LoginDao;
import com.lanou.bookstore.user.domain.User;
import com.lanou.bookstore.user.service.LoginService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/login.action")
public class LoginServlet extends HttpServlet {
    private LoginService loginService =
            new LoginService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = loginService.login(username, password);
        User user1 = loginService.login(username, password);
        if (user == null) {
            String msg="用户名/密码错误,点击返回登录页面";
            String path ="/login.jsp";
            request.setAttribute("msg",msg);
            request.setAttribute("path",path);
            response.setHeader("Refresh","5;URl=/login.jsp");
            request.getRequestDispatcher("msg.jsp").forward(request,response);
            //登录失败

        } else {
            //登录失败
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
        }
        response.sendRedirect("/index.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
